import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'function.dart';
import 'util/database.dart';
import 'model/group_model.dart';

class AddPage extends StatefulWidget {
  final List<GroupModel> groups;
  AddPage(this.groups);
  @override
  _AddPageState createState() => new _AddPageState(groups);
}

class _AddPageState extends State<AddPage> {
  _AddPageState(this.groups);
  List<GroupModel> groups;
  String selectedGroup="默认分组";
  final scaffoldState = GlobalKey<ScaffoldState>();
  String account = "";
  String password = "";
  bool showPass = false;
  final GlobalKey<FormState> _formKey = new GlobalKey<FormState>();
  @override
  void initState() {
    super.initState();
  }

//  initGroups() async {
//    var existGroups = await getGroups();
//    if (existGroups != null) {
//      for (var i = 0; i < existGroups.length; i++) {
//        groups.add(existGroups[i]['name']);
//      }
//    } else {
//      addGroup("默认分组");
//      groups.add("默认分组");
//    }
//    setState(() {});
//  }

  updateGroup() async {
    WankeData groups = new WankeData(tableName: "groups");
    groups.iniSqlite().then((db) {
      if (db != null) {
        print("test update");
        Map<String, dynamic> data;
        data = {"id": "1", "name": "测试分组xx"};
        groups.update(data).then((value) {
          print("update id:$value");
        });
      } else {
        print("not exist");
      }
    });
  }

  deleteGroup() async {
    WankeData groups = new WankeData(tableName: "groups");
    groups.iniSqlite().then((db) {
      if (db != null) {
        print("test delete");
        groups.deleteByColumn("id", "3").then((value) {
          print("delete id:$value");
        });
      } else {
        print("not exist");
      }
    });
  }

  String validateAccount(String value) {
    if (value == "") return "请输入手机号/邮箱";
    return null;
  }

  String validatePassword(String value) {
    if (value == "") return "请输入密码";
    return null;
  }

  login() async {
    var exist = await findDeviceByAccount(account);
    if (exist) {
      toast("账号已存在");
      return false;
    }
    Map loginInfo = await doLogin(account: account, password: password);
    if (loginInfo == null) {
      toast("登录出错");
    } else {
      var groupid=1;
      for(GroupModel group in groups){
        if(group.name==selectedGroup){
          groupid=group.id;
          break;
        }
      }
      int id = await addDevice(groupid, account, password, rand(), rand(), loginInfo['sessionid'], loginInfo['userid']);
      Navigator.pop(context, "$id");
    }
  }

  @override
  Widget build(BuildContext context){

    return new MaterialApp(
      theme: new ThemeData(
        accentColor: Colors.deepOrange,
        primaryColor: Colors.deepOrange,
      ),
      home: new Scaffold(
        key: scaffoldState,
        appBar: new CupertinoNavigationBar(
          actionsForegroundColor: Colors.white,
          backgroundColor: Colors.deepOrange,
          middle: new Text(
            "添加账号",
            style: new TextStyle(
              color: Colors.white,
              fontWeight: FontWeight.normal,
            ),
          ),
          leading: new CupertinoButton(
            padding: EdgeInsets.all(0.0),
            child: new Icon(
              CupertinoIcons.back,
              color: Colors.white,
            ),
            onPressed: () {
              Navigator.pop(context, null);
            },
          ),
        ),
        body: new Container(
          padding: EdgeInsets.all(20.0),
          child: new Form(
            key: _formKey,
            child: new Column(
              children: <Widget>[
                new TextFormField(
                  decoration: new InputDecoration(
                    hintText: '请输入手机号/邮箱',
                    labelText: "账号",
                  ),
                  onSaved: (value) {
                    account = value;
                  },
                  validator: validateAccount,
                ),
                new TextFormField(
                  obscureText: this.showPass,
                  decoration: new InputDecoration(
                    hintText: '请输入玩客云密码',
                    labelText: '密码',
                    suffixIcon: new IconButton(
                        icon: new Icon(
                          this.showPass ? Icons.visibility : Icons.visibility_off,
                          color: Colors.black38,
                          size: 22.0,
                        ),
                        onPressed: () {
                          this.showPass = !this.showPass;
                          setState(() {});
                        }),
                  ),
                  onSaved: (value) {
                    password = value;
                  },
                  validator: validatePassword,
                ),
                new DropdownButtonHideUnderline(
                  child: new SafeArea(
                    child: new InputDecorator(
                      decoration: const InputDecoration(
                        labelText: '分组',
                        hintText: '请选择分组',
                      ),
                      child: new DropdownButton<String>(
                        //style: TextStyle(color: Colors.black),
                        isDense: true,
                        value: selectedGroup,
                        onChanged: (value) {
                          setState(() {
                            selectedGroup = value;
                          });
                        },
                        items: groups.map((GroupModel group) {
                          return new DropdownMenuItem<String>(
                            value: group.name,
                            child: new Text(group.name),
                          );
                        }).toList(),
                      ),
                    ),
                  ),
                ),
                new Container(
                  decoration: new BoxDecoration(
                    borderRadius: new BorderRadius.all(new Radius.circular(20.0)),
                    color: Colors.deepOrange,
                  ),
                  margin: EdgeInsets.only(top: 20.0),
                  width: 160.0,
                  height: 40.0,
                  child: new FlatButton(
                      onPressed: () {
                        final FormState form = _formKey.currentState;
                        if (!form.validate()) {
                        } else {
                          form.save();
                          login();
                        }
                      },
                      child: new Text(
                        "确认添加",
                        style: new TextStyle(color: Colors.white),
                      )),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
